import sys, math
import urllib2
from BeautifulSoup import BeautifulSoup

# Download the Key Statistics given a ticker symbol
# Return Key Statistics and list of Keys
def downloadData(ticker):
  # Download Key Stats from http://finance.yahoo.com/q/ks?s=MA

  # Open URL
  #  myURL='http://ichart.finance.yahoo.com/table.csv?'+\
  #                       's=%s&d=10&e=20&f=2010&g=d&a=9&b=20&c=2010'%t +\
  #                       '&ignore=.csv'

  myURL='http://finance.yahoo.com/q/ks?s=%s'%ticker

  print myURL
  c=urllib2.urlopen(myURL)

  soup=BeautifulSoup(c.read())
  print soup

  keyCount=0
  #StringToFind="EPS"
  key=""
  value=""
  keys={}
  keyStats={}
  for td in soup('td'):
  # Prints the heading
    if ('class' in dict(td.attrs) and td['class']=='yfnc_tablehead1'):
      key=td.text
      keys[keyCount]=key
      keyCount=keyCount + 1
      print "*** Key is ***"
      print key
      continue
  # Prints the Value
    if ('class' in dict(td.attrs) and td['class']=='yfnc_tabledata1'):
        value=td.text
        print "*** value = ***"
        print value
        keyStats[key]=value
        continue

  #for k in keyStats:
  #   print keyStats[k]

  #print keyStats["Diluted EPS (ttm):"]
  print keyCount
  return keyStats, keys


def getValueFromKey( keyStats, key ):
  return keyStats[key]
  

EPS_KEY="Diluted EPS (ttm):"
PE_KEY="Trailing P/E (ttm, intraday):"
PEG_RATIO_KEY="PEG Ratio (5 yr expected)1:"
DEBT_KEY="Total Debt (mrq):"

#Is the Company Fairly Valued
def isFairlyValued( pegRatio ):
  if pegRatio <= 1:
     return True
  else:
     return False

# Does the Company have any debt?
def hasNoDebt( debt):
  if debt > 0:
    return False
  else:
    return True
  
 
def getRecommendation( keyStats):
  recommendation="Sell"
  pegRatio=float( getValueFromKey( keyStats, PEG_RATIO_KEY) )
  print "pegRatio is ", pegRatio

  debt=float( getValueFromKey( keyStats , DEBT_KEY ))
  print "debt is ", debt


  if ( isFairlyValued(pegRatio)):
    if ( hasNoDebt ):
       recommendation="Buy"
  return recommendation
  
# Start Script
if len(sys.argv) != 2:  # the program name and the ticker
  # stop the program and print an error message
  sys.exit("Must provide ticker")


ticker = sys.argv[1]


results , listOfKeys =downloadData(ticker)
#print listOfKeys
eps=float ( getValueFromKey( results, EPS_KEY) ) 
pe=float ( getValueFromKey( results, PE_KEY) )

print "eps=" , eps
print "pe=" , pe
price = eps * pe
print "price=" , price

recommendation=getRecommendation( results ) 
print "*** Recommendation for " , ticker  , "is " , recommendation , " *** "
